import { Context, Next } from 'koa';
import DeviceService from '../../service/Admin/Device.service'
import TcpClient from '../../until/Tcp';
interface Device {
    id: number;
    ip: string;
    isConnected: boolean;
    name: string;
}
class DeviceController { 
 // 获取模块的数量
    async getModuleNum(ctx:Context) {
       let result = await DeviceService.getModuleNum()
        ctx.body = {
            code: 200,
            msg: "获取成功",
            data: result
        }
    }
     // 获取监测点报警的排行列表
    async getSortPoint(ctx:Context) {
        let gatewayIp: string | string[] | undefined = ctx.query.gatewayIp; // 获取网关IP参数
        let result = await DeviceService.getSortPoint(gatewayIp as string);
        
        ctx.body = {
            code: 200,
            msg: "获取数据成功",
            data: result
        }
    }

  // 获取接入的网关列表
   public async getGatewayList(ctx: Context) {
    try {
        const tcpClient = TcpClient.getInstance();
        const ipList: Device[] = tcpClient.getAllConnectionsStatus();

        ipList.sort((a: Device, b: Device) => Number(a.ip.split('.')[3]) - Number(b.ip.split('.')[3]))
        if (ipList.length === 0) {
            ctx.body = {
                code: 204,
                msg: "暂无网关连接，请检查网络状态",
                data: []
            };
        } else {
            ctx.body = {
                code: 200,
                msg: "获取接入的网关列表成功",
                data: ipList
            };
        }
    } catch (err) {
        ctx.body = {
            code: 500,
            msg: "服务器内部错误",
            data: []
        };
    }
}
}

export default new DeviceController();